package com.jianbing.shasha.controller;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSON;
import com.jianbing.common.core.domain.AjaxResult;
import com.jianbing.common.utils.file.FileUploadUtils;
import com.jianbing.common.utils.file.FileUtils;
import com.jianbing.common.utils.uuid.UUID;
import com.jianbing.framework.config.ServerConfig;
import com.jianbing.shasha.mapper.ShashaVoiceAnsMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/shasha")
public class ShashaFileController {

//    private final String filePath = "/shasha/";

    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private ShashaVoiceAnsMapper shashaVoiceAnsMapper;

    private static final Logger log = LoggerFactory.getLogger(ShashaFileController.class);

    @PostMapping("/upload")
    public AjaxResult uploadFile(@RequestParam("level") Long level,@RequestParam("file") MultipartFile file) throws Exception
    {
        AjaxResult ajax = AjaxResult.success();
        Long type =  (level-1)%4;
        String emotionType = null;
        if(type==0){
            emotionType = "happy";
        } else if (type==1) {
            emotionType = "sad";
        }else if (type==2) {
            emotionType = "angry";
        }else if (type==3) {
            emotionType = "fear";
        }
        List<String> keyWord = shashaVoiceAnsMapper.selectShashaVoiceAnsByEmotionType(emotionType);
//        HttpUtils.sendPost("http://47.113.227.126:1002/upload",)
//        String text = dataPost("http://47.113.227.126:1002/upload", file);

        try
        {
//            // 上传文件路径
//            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(file);
            String url = serverConfig.getUrl() + fileName;
//            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }

        File toFile = transferToFile(file);
        String text,text2;
        try {
            text = doPostFormDataFile("http://47.113.227.126:1002/upload", "audio", toFile, null, 40);
            log.info("http://47.113.227.126:1002/upload" + text);
//            text2 = doPostFormDataFile("https://yunpan.windbless.top/asr?encode=true&task=transcribe&language=zh&word_timestamps=false&output=txt", "audio_file", toFile, null, 400);
//            log.info("https://yunpan.windbless.top/asr?encode=true&task=transcribe&language=zh&word_timestamps=false&output=txt" + text2);
        }finally {
            if(toFile!=null){
                toFile.delete();
            }
        }

        for(String word:keyWord){
            if(text.contains(word)){
                ajax.put("correct",1);
                break;
            }
//            if(text2.contains(word)){
//                ajax.put("correct",1);
//                break;
//            }
        }

        if(!ajax.containsKey("correct")){
            ajax.put("correct",0);
        }
        return ajax;
    }

    /**
     * 发送post请求 携带文件
     *
     * @param url
     * @param fileParamName
     * @param File
     * @param otherFormDataMap
     * @param connectTimeout
     * @return java.lang.String
     * @author zheng
     * @create 2024/6/17
     **/
    private  String doPostFormDataFile(String url, String fileParamName, File toFile, Map<String, String> otherFormDataMap,
                                       int connectTimeout) throws IOException {
//        File toFile = null;
//          toFile = transferToFile(multipartFile);
        Map<String, Object> data = new HashMap<>();
        data.put(fileParamName, toFile);
//            data.putAll(otherFormDataMap);
        String response = HttpRequest.post(url)
                .form(data)
                .contentType("multipart/form-data")
                .setConnectionTimeout(connectTimeout)
                .execute()
                .body();
        return response;
    }

    public static File transferToFile(MultipartFile multipartFile) throws IOException {
        //选择用缓冲区来实现这个转换即使用java 创建的临时文件 使用 MultipartFile.transferto()方法 。
        File file = null;
        try {
            String originalFilename = multipartFile.getOriginalFilename();
            //获取文件后缀
            String prefix = originalFilename.substring(originalFilename.lastIndexOf("."));
            //创建临时文件
            String fileName = UUID.randomUUID().toString().replace("_","");
            file = File.createTempFile(fileName, prefix);
            multipartFile.transferTo(file);
            //在这里使用deleteOnExit()会出现文件删除不掉的情况，而使用delete()会导致请求报错
//            file.deleteOnExit();
        } catch (IOException e) {
            log.error("transferToFile--异常：", e);
            throw e;
        }
        return file;
    }


}
